package com.gm.wholesale.module.order.ui;

import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment;
import com.gm.commonlib.module.evenbus.EventBusUtils;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.timePickerView.TimePickerViewUtils;
import com.gm.commonlib.views.timePickerView.listener.OnTimeSelectListener;
import com.gm.wholesale.R;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.order.orderStatus.OrderStatusType;
import com.gm.wholesale.module.order.api.IOrderApi;
import com.gm.wholesale.module.order.bean.OrderBean;
import com.gm.wholesale.module.order.bean.OrderDetailBean;
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime;

import java.util.Date;
import java.util.List;

import io.reactivex.Observable;

public class OrderListFragment extends BaseListFragment<OrderBean, BasePageData<OrderBean>> implements ISearchOrderByTime {

     private String mOrderingTimeBegin;
    private String mOrderingTimeEnd;

    private View headerView;

    public void updateView(){
        mOrderingTimeBegin=null;
        refreshData();
    }



    @Override
    protected void onCreateContentHeader(ViewGroup parent) {
        super.onCreateContentHeader(parent);
        headerView=  LayoutInflater.from(context).inflate(R.layout.view_order_header,parent);
       TextView choiceTimeTv=headerView.findViewById(R.id.choiceTimeTv);
       String time=DateTimeUtils.formatDateTime(System.currentTimeMillis(),DateTimeUtils.HMD2);
        choiceTimeTv.setText(time+"(今天)");
       choiceTimeTv.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               long nowTime=System.currentTimeMillis();
               if (!TextUtils.isEmpty(mOrderingTimeBegin)){
                   nowTime=DateTimeUtils.getTimeStringToLong(mOrderingTimeBegin, DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
               }
               TimePickerViewUtils.showTimeByYMD(context,"选择时间", nowTime,new OnTimeSelectListener() {
                   @Override
                   public void onTimeSelect(Date date, View v) {
                       mOrderingTimeBegin=DateTimeUtils.formatDateTime(date,DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
                       mOrderingTimeEnd=mOrderingTimeBegin+" 23:59:59";
                       mOrderingTimeBegin=mOrderingTimeBegin+" 00:00:00";
                      String time=DateTimeUtils.formatDateTime(date,DateTimeUtils.HMD2);
                      if (DateTimeUtils.isToday(date)){
                          time=time+"(今天)";
                      }
                      choiceTimeTv.setText(time);
                       refreshData();
                   }
               });
           }
       });
       hidHeaderView();
    }

    public void showHeaderView(){
        headerView.setVisibility(View.VISIBLE);
    }

    public void hidHeaderView(){
        headerView.setVisibility(View.GONE);
    }


    @Override
    public void initPullToRefreshListView() {
        super.initPullToRefreshListView();
      setBodybg(getResources().getColor(R.color.white));
      pullToRefreshListView.setDivider(getResources().getDrawable(R.drawable.list_driver_shap));

    }
    OrderMangerFragment mOrderMangerFragment;
    public void setOrderMangerFragment(OrderMangerFragment orderMangerFragment){
        mOrderMangerFragment=orderMangerFragment;
    }


    @Override
    protected void getDataFinish(List<OrderBean> mDatas) {
        if (mDatas!=null && !mDatas.isEmpty()){
            mDatas.get(0).setClick(true);
            showOrderDetail(mDatas.get(0));
        }
        else {
            if (mOrderMangerFragment==null)return;
            mOrderMangerFragment.hasNotOrderData();
        }
    }

    @Override
    protected BaseAdapter createTempBaseAdapter() {
        return new CommonAdapter<>(getActivity(), mDatas, R.layout.list_order_manger_item) {
            @Override
            public void convert(ViewHolder viewHolder, final OrderBean data) {
                if (data.isClick()){
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.color_e4f4eb));
                }
                else {
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.white));
                }
                TextView aftersaTv=viewHolder.getView(R.id.afterOrderNt);
                aftersaTv.setVisibility(View.GONE);
                if (data.isAftersale()){
                    aftersaTv.setVisibility(View.VISIBLE);
                }
                viewHolder.setText(R.id.userNameTv,data.getCustomerName());
                viewHolder.setText(R.id.orderNumTv,data.getOrderNo());
                viewHolder.setText(R.id.orderPriceTv,"￥"+data.getSalesAmount());
                viewHolder.setText(R.id.createTimeTv, data.getOrderingTime());
                showOrderState(data,viewHolder.getView(R.id.orderStateTv));
                viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        setDataClick(data);
                        notifyDataSetChanged();
                        showOrderDetail(data);

                    }
                });
            }
        };

    }

    private void showOrderDetail(OrderBean orderBean){
        EvenBusUtil.updateOrderDetail(orderBean);
    }

    private void setDataClick(OrderBean clickData){
        for (OrderBean data:mDatas){
            if (data.getOrderId()==clickData.getOrderId()){
                data.setClick(true);
            }
            else {
                data.setClick(false);
            }
        }

    }


    private void showOrderState(OrderBean data, TextView textView){
        int payStatus=data.getPaidStatus();
        if (payStatus== OrderStatusType.WWC.getType()){
            textView.setText("未支付");
            textView.setTextColor(context.getResources().getColor(R.color.color_FF4D4F));
        }
       else if (data.getPaidStatus()==OrderStatusType.YYS.getType()){
            textView.setText("已结清");
            textView.setTextColor(context.getResources().getColor(R.color.color_06AE56));
        }
       else {
            textView.setText("未结清");
            textView.setTextColor(context.getResources().getColor(R.color.color_FF4D4F));
        }
    }

    @Override
    protected HttpServicesHolder<?, BasePageData<OrderBean>> getHttpServicesHolder(long index) {
        return new HttpServicesHolder<IOrderApi, BasePageData<OrderBean>>() {
            @Override
            public Observable<BasePageData<OrderBean>> getHttpObservable(IOrderApi api) {
                ArrayMap<String, Object> quearyData= getArrayMap();
                quearyData.put("page",index);
                quearyData.put("pageSize", Constant.DEFAULTPAGESIZE);
                return api.getOrderList(quearyData);
            }
        };
    }

    public ArrayMap<String, Object> getArrayMap(){
        //订单类型，1-小程序现场单，2-小程序提前单，3-批发版现场单
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("type",3);
        if (TextUtils.isEmpty(mOrderingTimeBegin)){
            mOrderingTimeBegin=DateTimeUtils.formatDateTime(System.currentTimeMillis(),DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
            mOrderingTimeEnd=mOrderingTimeBegin+" 23:59:59";
            mOrderingTimeBegin=mOrderingTimeBegin+" 00:00:00";
        }
        queryData.put("orderingTimeStart",mOrderingTimeBegin);
        queryData.put("orderingTimeEnd",mOrderingTimeEnd);


        return queryData;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
       if (event.getCode()==EventBusType.UPDATE_ORDER_LIST.getType()){
          updateListView((OrderDetailBean) event.getData());
       }
    }

    public void updateListView(OrderDetailBean orderDetailBean){
        OrderDetailBean.OrderInfoDTO orderInfoDTO= orderDetailBean.getOrderInfo();
        if (orderInfoDTO==null || mDatas.isEmpty()){
            return;
        }
        for (OrderBean orderBean:mDatas){
            if (orderInfoDTO.getOrderId()==orderBean.getOrderId()){
                orderBean.setPaidStatus(orderInfoDTO.getPaidStatus());
                notifyListDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void searchOrderByTime(String begTime, String endTime) {
        mOrderingTimeBegin=begTime;
        mOrderingTimeEnd=endTime;
        refreshData();
    }


}
